<template>
  <div class="app-container">
    <el-container style="height: 780px; border: 1px solid #eee">
      <div class="filter-container">
        <el-form ref="queryForm" :model="listQuery" :rules="queryRules" label-position="left">
          <el-form-item size="mini" prop="partner_name" style="float: left;">
            <el-input v-model="listQuery.partner_name" placeholder="请输入租户名称" class="filter-item" style="width: 160px;margin-right:5px;"></el-input>
          </el-form-item>
          <el-form-item size="mini" prop="partner_sign" style="float: left;">
            <el-input v-model="listQuery.partner_sign" placeholder="请输入租户标识" class="filter-item" style="width: 160px;margin-right:5px;"></el-input>
          </el-form-item>
          <el-button v-waves size="mini" class="filter-item" type="primary" icon="el-icon-search" @click="getList">查询</el-button>
          <el-button v-waves size="mini" class="filter-item" type="danger" @click="resetQueryForm('queryForm')">重置</el-button>
        </el-form>
      </div>
      <el-table v-loading="listLoading" :data="list" size="mini" highlight-current-row style="width: 100%">
        <el-table-column width="50px" align="left" label="ID">
          <template slot-scope="{row}">
            <span>{{ row.Id }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="租户名称">
          <template slot-scope="{row}">
            <span>{{ row.PartnerName }}</span>
          </template>
        </el-table-column>
        <el-table-column  align="left" label="头像">
          <template slot-scope="{row}">
            <img :src="row.Avatar" width="38px" height="38px">
          </template>
        </el-table-column>
        <el-table-column width="100px" align="left" label="Sign">
          <template slot-scope="{row}">
            <span>{{ row.PartnerSign }}</span>
          </template>
        </el-table-column>
        <el-table-column width="100px" align="left" label="密钥">
          <template slot-scope="{row}">
            <span>{{ row.Key }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="描述">
          <template slot-scope="{row}">
            <span>{{ row.Remark }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="{row}">
            <el-button
              type="primary"
              size="small"
              icon="el-icon-edit"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="handleStatus(row.Id)"
            >
              下架
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination style="margin-top: 1px; padding-top: 10px;" v-show="+total > 0" :total="total" :page.sync="listQuery.page_index" :limit.sync="listQuery.page_size" @pagination="getList" />
    </el-container>
    <el-dialog>
      <div class="container" style="width: 100%;">
          <el-divider content-position="center">
            <div v-if="isEdit" style="color: red;">编辑租户 - {{addData.id}}</div>
            <div v-if="!isEdit">新增商品</div>
          </el-divider>
          <el-form ref="addForm" :rules="rules" :model="addData" label-position="left" label-width="90px" style="padding-left: 10px; padding-top: 15px;">
            <el-form-item label="租户名称" size="mini" prop="partner_name" style="width: 325px;">
              <el-input v-model="addData.partner_name" placeholder="汉字,字母,数字,下划线，6-36长度"/>
            </el-form-item>
            <el-form-item label="租户标识" size="mini" prop="partner_sign" style="width: 325px;">
              <el-input v-model="addData.partner_sign" placeholder="字母,数字，4-16长度"/>
            </el-form-item>
            <el-form-item label="租户描述" size="mini" prop="remark" style="width: 325px;">
              <el-input
                v-model="addData.remark"
                type="textarea"
                placeholder="标签自动过滤，2-128长度"
                maxlength="128"
                show-word-limit
              >
              </el-input>
            </el-form-item>
            <el-form-item label="租户头像" prop="avatar">
              <el-upload
                class="avatar-uploader"
                :action="imageUploadUrl"
                :show-file-list="false"
                :headers="uploadHeader"
                :on-success="handleUploadAvatarImageSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="imageAvatarUrl" :src="imageAvatarUrl" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button style="float: right; margin-right: 100px;" size="mini" type="primary" @click="handleAddSubmit()">提交</el-button>
            <el-button style="float: right; margin-right: 12px;" size="mini" v-waves type="primary" @click="resetQueryForm('addForm')">重置</el-button>
          </div>
        </div>
    </el-dialog>
  </div>
</template>

<script>
import { goodsList, goodsAdd, goodsStatus } from '@/api/secondhand'
import waves from '@/directive/waves'
import Pagination from '@/components/Pagination/index'
import { getToken } from '@/utils/auth'
import { strLength } from '@/utils/common'
import { checkCanAccess } from '@/utils/permission'

export default {
  name: 'PartnerList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        '0': '禁用',
        '1': '启用'
      }
      return statusMap[status]
    }
  },
  data() {
    const checkName = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 租户名不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 36 || strLen < 6) {
        return callback(new Error('对不起， 租户名长度为6-36个字符,汉字为3个字符!'))
      }

      const reg = /^[A-Za-z0-9\u4e00-\u9fa5]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 租户名只能包含汉字,数字,字母'))
      } else {
        callback()
      }
    }
    const checkSign = function(rule, value, callback) {
      if (!value) {
        return callback(new Error('对不起， 租户标识不能为空!'))
      }

      const strLen = strLength(value)
      if (strLen > 16 || strLen < 4) {
        return callback(new Error('对不起， 租户标识长度为4-16个字符!'))
      }

      const reg = /^[A-Za-z]+[A-Za-z0-9]+$/
      if (!reg.test(value)) {
        callback(new Error('对不起, 只能字母和数字,并且字母开头'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page_index: 1,
        page_size: 10,
        partner_name: '',
        partner_sign: ''
      },
      addData: {
        id: 0,
        partner_name: '',
        partner_sign: '',
        avatar: '',
        remark: ''
      },
      isEdit: false,
      imageAvatarUrl: '',
      imageUploadUrl: process.env.VUE_APP_BASE_API + 'tenant/partner/uploadAvatar',
      rules: {
        partner_name: [
          { required: true, message: '需要填写租户名称', trigger: 'blur' },
          { validator: checkName, trigger: 'blur' }
        ],
        partner_sign: [
          { required: true, message: '需要填写租户Sign', trigger: 'blur' },
          { validator: checkSign, trigger: 'blur' }
        ],
        remark: [
          { required: true, message: '需要填写租户描述', trigger: 'blur' },
          { min: 2, max: 128, message: '长度在 2 到 128 个字符之间', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '需要填写确认头像', trigger: 'blur' },
          { min: 6, max: 64, message: '长度在 6 到 64 个字符之间', trigger: 'blur' }
        ]
      },
      queryRules: {
        partner_name: [
          { required: false, message: '需要填写租户名称', trigger: 'blur' }
        ],
        partner_sign: [
          { required: false, message: '需要填写租户标识', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    uploadHeader() {
      return { Authorization: 'bearer ' + getToken() }
    }
  },
  created() {
    this.resetQueryData()
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      goodsList(this.listQuery).then(response => {
        if (response.success) {
          this.list = response.data.data
          this.total = response.data.total
          setTimeout(() => {
            this.listLoading = false
          }, 300)
        } else {
          this.$message({
            type: 'error',
            message: response.msg
          })
          setTimeout(() => {
            this.listLoading = false
          }, 100)
        }
      })
    },
    getDetail(item) {
      this.addData.partner_name = item.PartnerName
      this.addData.partner_sign = item.PartnerSign
      this.addData.avatar = item.Avatar
      this.addData.id = item.Id
      this.addData.remark = item.Remark

      this.imageAvatarUrl = item.Avatar
    },
    handleEdit(item) {
      this.isEdit = true
      this.getDetail(item)
    },
    handleAddSubmit() {
      this.$refs['addForm'].validate((valid) => {
        if (valid) {
          goodsAdd(this.addData).then((response) => {
            if (response.success === true) {
              this.$message({
                type: 'success',
                message: '添加权限成功'
              })
              this.getList()
              this.resetAddData()
            } else {
              this.$message({
                type: 'error',
                message: response.msg
              })
            }
          }).catch(err => {
            this.$message({
              type: 'error',
              message: err
            })
          })
        }
      })
    },
    handleStatus(id) {
      this.$confirm('此操作将永久删除权限,并删除角色已分配,用户已分配, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        goodsStatus(id).then((response) => {
          if (response.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getList()
          } else {
            this.$message({
              type: 'error',
              message: response.msg
            })
          }
        }).catch(err => {
          this.$message({
            type: 'success',
            message: err
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetAddData() {
      this.imageAvatarUrl = ''
      this.isEdit = false
      this.$refs['addForm'].resetFields()
      this.addData = {
        id: 0,
        partner_name: '',
        partner_sign: '',
        avatar: '',
        remark: ''
      }
    },
    resetQueryData() {
      this.listQuery = {
        page_index: 1,
        page_size: 10,
        partner_name: '',
        partner_sign: '',
        remark: ''
      }
    },
    resetQueryForm(formName) {
      this.resetAddData()
      this.$refs[formName].resetFields()
    },
    beforeAvatarUpload(file) {
      if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
        this.$message.error('上传头像图片只能是 JPG/PNG 格式!')
        return false
      }

      if (file.size / 1024 > 200) {
        this.$message.error('上传头像图片大小不能超过 200K!')
        return false
      }
      return true
    },
    handleUploadAvatarImageSuccess(res, file) {
      if (res.success) {
        this.addData.avatar = res.data.file_name
        this.imageAvatarUrl = URL.createObjectURL(file.raw)
      } else {
        this.$message({
          type: 'error',
          message: '上传图片失败'
        })
      }
    },
    checkCanAccess(path) {
      return checkCanAccess(path)
    }
  }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>
